<?php
session_start();
$pageTitle = "文章详情";
include 'includes/functions.php';

// 获取文章ID
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$article = getArticleById($id);

if (!$article) {
    header('Location: index.php');
    exit;
}

// 获取文章分类
$articleCategories = getArticleCategories($id);

// 增加浏览量
incrementViewCount($id);

// 检查是否为文章作者（仅当用户已登录时）
$isOwner = false;
if (isset($_SESSION['user'])) {
    $isOwner = isArticleOwner($id, $_SESSION['user']['user_id']);
}

include 'includes/header.php';
?>

<div class="container">
    <div class="article-header">
        <h1><?php echo htmlspecialchars($article['title']); ?></h1>
        <div class="article-meta">
            <span><i class="far fa-user"></i> <?php echo htmlspecialchars($article['display_name'] ?? $article['author']); ?></span>
            <span><i class="far fa-calendar"></i> <?php echo date('Y-m-d H:i', strtotime($article['created_at'])); ?></span>
            <span><i class="far fa-eye"></i> <?php echo $article['view_count']; ?>次阅读</span>
            <span class="status-badge <?php echo $article['status']; ?>">
                <?php echo $article['status'] === 'published' ? '已发布' : '草稿'; ?>
            </span>
        </div>
        <?php if (!empty($articleCategories)): ?>
        <div class="article-categories">
            <i class="fas fa-tags"></i>
            <?php $category = $articleCategories[0]; ?>
            <a href="category.php?id=<?php echo $category['category_id']; ?>" class="category-tag">
                <?php echo htmlspecialchars($category['name']); ?>
            </a>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- <div class="article-image" style="background-image: url('<?php echo $article['image']; ?>')"></div> -->
    
    <div class="article-content">
        <?php echo nl2br(htmlspecialchars($article['content'])); ?>
    </div>
    
    <?php if ($isOwner): ?>
    <div class="article-actions">
        <a href="edit.php?id=<?php echo $article['post_id']; ?>" class="btn btn-primary">
            <i class="fas fa-edit"></i> 编辑文章
        </a>
        <button class="btn btn-danger" id="delete-article-btn" data-id="<?php echo $article['post_id']; ?>">
            <i class="fas fa-trash"></i> 删除文章
        </button>
        <a href="index.php" class="btn btn-accent">
            <i class="fas fa-arrow-left"></i> 返回首页
        </a>
    </div>
    <?php else: ?>
    <div class="article-actions">
        <a href="index.php" class="btn btn-accent">
            <i class="fas fa-arrow-left"></i> 返回首页
        </a>
        <?php if (!isset($_SESSION['user'])): ?>
        <a href="login.php" class="btn btn-primary">
            <i class="fas fa-sign-in-alt"></i> 登录后发布文章
        </a>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<?php if ($isOwner): ?>
<script>
document.getElementById('delete-article-btn')?.addEventListener('click', function() {
    const postId = this.getAttribute('data-id');
    
    if (confirm('确定要删除这篇文章吗？此操作不可撤销。')) {
        const formData = new FormData();
        formData.append('action', 'delete_article');
        formData.append('post_id', postId);
        
        fetch('api.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(data.message);
                window.location.href = 'index.php';
            } else {
                alert(data.error || '删除失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('删除失败，请重试');
        });
    }
});
</script>
<?php endif; ?>

<?php include 'includes/footer.php'; ?>